package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"time"
)

func GetActivities(ctx *gin.Context) {
	Uid := ctx.Query("uid")
	uid, _ := strconv.Atoi(Uid)

	// 查询数据库
	DB := common.GetDB()
	var activities []model.Activity

	err := DB.Where("State != ?", 0).Find(&activities).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}

	//判断活动举办的社团名称
	dB := common.GetDB()

	var clubNames []string
	for _, activity := range activities {
		var clubs []model.Club
		err1 := dB.Where("id=?", activity.Cid).First(&clubs).Error
		if err1 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err1:", err1)
			return
		}
		for _, club := range clubs {
			clubNames = append(clubNames, club.Cname)
		}
	}

	//判断活动是否被收藏
	db := common.GetDB()
	var collected []int
	for _, activity := range activities {
		var count int
		err2 := db.Model(&model.ActivityCollection{}).Where("aid=? AND uid =?", activity.Aid, uid).Count(&count).Error
		if err2 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err2:", err2)
			return
		}
		if count > 0 {
			collected = append(collected, 1)
		} else {
			collected = append(collected, 0)
		}
	}

	// 返回查询结果
	response.Success(ctx, gin.H{"activities": activities, "clubNames": clubNames, "collected": collected}, "获取成功")
}

// 收藏或取消收藏活动
func CollectActivity(ctx *gin.Context) {
	// 获取用户ID和活动ID,并转换为int
	Uid := ctx.PostForm("uid")
	uid, err := strconv.Atoi(Uid)
	Aid := ctx.PostForm("aid")
	aid, err1 := strconv.Atoi(Aid)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 422, nil, "警告！警告！")
		return
	}

	if err1 != nil {
		response.Response(ctx, http.StatusBadRequest, 422, nil, "警告，警告！")
		return
	}

	// 获取收藏状态
	collected := ctx.PostForm("collected")

	DB := common.GetDB()
	if collected == "0" {
		// 创建收藏记录
		newcollection := model.ActivityCollection{
			Uid: uid,
			Aid: aid,
		}

		err2 := DB.Create(&newcollection).Error
		// 将收藏记录保存到数据库
		if err != nil {
			response.Response(ctx, http.StatusInternalServerError, 400, nil, "收藏活动失败，请重试")
			log.Println("err2", err2)
			return
		}
		response.Response(ctx, http.StatusOK, 200, nil, "收藏活动成功")
	} else {
		// 删除收藏记录
		var collection model.ActivityCollection
		err3 := DB.Where("uid=? AND aid=?", uid, aid).Delete(&collection).Error
		if err3 != nil {
			response.Response(ctx, http.StatusInternalServerError, 400, nil, "取消收藏失败，请重试")
			log.Println("err3", err3)
			return
		}
		//  返回结果
		response.Response(ctx, http.StatusOK, 200, nil, "取消收藏活动成功")
	}
}

func JoinActivity(ctx *gin.Context) {
	Uid := ctx.PostForm("uid")
	uid, _ := strconv.Atoi(Uid)
	Aid := ctx.PostForm("aid")
	aid, _ := strconv.Atoi(Aid)
	Time := ctx.PostForm("time")

	db := common.GetDB()
	activityApply := model.ActivityApply{}
	//是否参加了该活动并在审批中
	db.Where("UID=? AND id=? and Result=?", uid, aid, 0).First(&activityApply)
	if activityApply.ID != 0 {
		response.Success(ctx, gin.H{"permission": 1}, "您已报名参加")
		return
	}

	//是否参加了该活动并报名成功
	db.Where("UID=? AND id=? and Result=?", uid, aid, 1).First(&activityApply)
	if activityApply.ID != 0 {
		response.Success(ctx, gin.H{"permission": 2}, "您已报名成功")
		return
	}

	// 还未参加活动或参与失败，查询对应的活动
	var activity model.Activity
	err1 := db.Where("id=?", aid).First(&activity).Error
	if err1 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
	}

	//如果仅社内成员参加，判断是否是社内成员
	if activity.Permission == 1 {
		var joinedClubs []model.UserClub
		result := db.Where("Cid = ? AND UID = ?", activity.Cid, uid).Where("QuitTime IS NULL").Find(&joinedClubs)
		if result.Error != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询时发生错误!")
			return
		}
		count := result.RowsAffected

		//不是社内成员
		if count == 0 {
			response.Success(ctx, gin.H{"permission": 3}, "您没有权限参加该活动")
			return
		} else { //是社内成员:
			applyTime, _ := time.Parse("2006-01-02 15:04:05", Time)
			newActivityApply := model.ActivityApply{
				Aid:       aid,
				SID:       uid,
				ApplyTime: applyTime,
			}

			err := db.Create(&newActivityApply).Error
			if err != nil {
				response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入活动申请失败，请重试！")
				return
			}

			joinActivity_id := newActivityApply.ID
			fmt.Println(joinActivity_id)
			newApply := model.Apply{
				Apply_ID:       joinActivity_id,
				UserID:         uid,
				Kind:           1,
				Approval_State: 0,
				Title:          activity.ATitle,
				ApplyTime:      newActivityApply.ApplyTime,
			}
			err1 := db.Create(&newApply).Error
			if err1 != nil {
				response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入总申请失败，请重试！")
				return
			}
			response.Success(ctx, gin.H{"permission": 0}, "报名成功")
			return
		}
	} else {
		tx := db.Begin()
		if tx.Error != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "无法开始事务，请重试！")
			return
		}
		applyTime, _ := time.Parse("2006-01-02 15:04:05", Time)
		newActivityApply := model.ActivityApply{
			Aid:       aid,
			SID:       uid,
			ApplyTime: applyTime,
		}
		err := tx.Create(&newActivityApply).Error
		if err != nil {
			tx.Rollback() // 回滚事务
			response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入活动申请失败，请重试！")
			return
		}

		joinActivity_id := newActivityApply.ID
		newApply := model.Apply{
			Apply_ID:       joinActivity_id,
			UserID:         uid,
			Kind:           1,
			Approval_State: 0,
			Title:          activity.ATitle,
			ApplyTime:      newActivityApply.ApplyTime,
		}
		// 在事务中创建newApply
		err1 := tx.Create(&newApply).Error
		if err1 != nil {
			tx.Rollback() // 回滚事务
			response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入总申请失败，请重试！")
			return
		}
		// 提交事务
		err2 := tx.Commit().Error
		if err2 != nil {
			tx.Rollback() // 回滚事务
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "提交事务失败，请重试！")
			return
		}
		response.Success(ctx, gin.H{"permission": 0}, "报名成功")
		return
	}
}
